let http = require('http');
let server = http.createServer();

let io = require('socket.io')(server);
const PORT = 3000;

//客户端计数
let clientCount = 0;
//记录客户端
let clientMap = {};

/**
 * 绑定事件监听
 * @param  {[type]} socket [description]
 * @param  {[type]} event  [description]
 * @return {[type]}        [description]
 */
function bingListener(socket, event){
	socket.on(event, function(data){
		if(socket.clienNumber % 2 == 0){
			if(clientMap[socket.clienNumber-1]){
				clientMap[socket.clienNumber-1].emit(event, data);
			}
		}else{
			if(clientMap[socket.clienNumber+1]){
				clientMap[socket.clienNumber+1].emit(event, data);
			}
		}
	})
}

io.on('connection', function(socket){
	clientCount++;
	socket.clienNumber = clientCount;
	clientMap[clientCount] = socket;

	if(clientCount % 2 == 1){
		socket.emit('waiting', '等待中...');
	}else{
		socket.emit('start');
		if(clientMap[socket.clienNumber-1]){
			clientMap[socket.clienNumber-1].emit('start');
		}
	}

	bingListener(socket, 'init');
	bingListener(socket, 'next');
	bingListener(socket, 'rotate');
	bingListener(socket, 'down');
	bingListener(socket, 'left');
	bingListener(socket, 'right');
	bingListener(socket, 'fall');
	bingListener(socket, 'fixed');
	bingListener(socket, 'line');
	bingListener(socket, 'time');
	bingListener(socket, 'lost');
	bingListener(socket, 'addLines');

	socket.on('disconnect', function(){
		if(socket.clienNumber % 2 == 0){
			if(clientMap[socket.clienNumber-1]){
				clientMap[socket.clienNumber-1].emit('leave');
			}
		}else{
			if(clientMap[socket.clienNumber+1]){
				clientMap[socket.clienNumber+1].emit('leave');
			}
		}
		delete(clientMap[socket.clienNumber]);
	});
});

server.listen(PORT);




console.log('Server is listenning PORT '+ PORT);